/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.web.controller;

import cc.altius.domain.Role;
import cc.altius.domain.User;
import cc.altius.service.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

/**
 *
 * @author Akil Mahimwala
 */
@Controller
@RequestMapping("/admin/userAdd.htm")
@SessionAttributes("user")
public class AddUserController {

    @Autowired
    private UserService userService;

    @ModelAttribute("roleList")
    public List<Role> populateRoleList() {
        return this.userService.getRoleList();
    }

    @RequestMapping(method = RequestMethod.GET)
    public String showAddUserForm(ModelMap model) {
        User user = new User();
        model.addAttribute("user", user);
        return "/admin/userAdd";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(@ModelAttribute("user") User user, Errors errors, SessionStatus status) {
        if (this.userService.existUserByUsername(user.getUsername())) {
            errors.rejectValue("username", "msg.duplicateUser");
            return "/admin/userAdd";
        }
        int userId = this.userService.addUser(user);
        if (userId==0) {
            errors.rejectValue("username","msg.userError");
            return "/admin/userAdd";
        } else {
            status.setComplete();
            return "redirect:/admin/userList.htm?msg=msg.userAddedSuccessfully";
        }
    }
}
